package database;

import java.util.ArrayList;

import model.Group;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class GroupAdapter {
	private static final String DATABASE_NAME = "groupsdb";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase db;
	private GroupHelper dbHelper;
	private Context ctx;
	
	
	public static final String TABLE_NAME1="groups";
	public static final String KEY_ROWID = "_id";
	public static final String KEY_NAME="GROUP_NAME";
	
	public GroupAdapter(Context ctx){
		this.ctx=ctx;
	}
	public GroupAdapter open(){
		dbHelper = new GroupHelper(ctx, DATABASE_NAME, null, DATABASE_VERSION);
		db=dbHelper.getWritableDatabase();
		return this;
	}
	public void close(){
		dbHelper.close();
	}
	public long createGroup(Group gp){
		Log.d("GROUPSMS","creating a new group");
		ContentValues initialValues = new ContentValues();
	    initialValues.put(KEY_NAME, gp.getGroupName());
	    return db.insert(TABLE_NAME1, null, initialValues);
	}
	public Cursor fetchAllGroups(){
		String colNames[]={KEY_ROWID,KEY_NAME};
		dbHelper.onCreate(db);
		Cursor allGroups = db.query(TABLE_NAME1, colNames, null, null, null, null, null);
		return allGroups;
	}
	public boolean deleteGroup(long _id){
		return db.delete(TABLE_NAME1, KEY_ROWID+ '=' +_id, null)>0;
	}
	public ArrayList<Group> fetchGroups(){
		ArrayList<Group> list=new ArrayList<Group>();
		Cursor c=fetchAllGroups();
		if(c!=null){
			while(c.moveToNext()){
				int id=c.getInt(c.getColumnIndexOrThrow(KEY_ROWID));
				String name=c.getString(c.getColumnIndexOrThrow(KEY_NAME));
				Group g=new Group(id,name);
				list.add(g);
			}
		}
		c.close();
		return list;
	}
}
